package com.nlecloud.bc.service.contract.impl;

import com.nlecloud.bc.config.PhantomjsConfig;
import com.nlecloud.bc.constant.CustomerConstant;
import com.nlecloud.bc.contract.Infringement;
import com.nlecloud.bc.controller.contract.dto.InfringementDTO;
import com.nlecloud.bc.interceptor.AuthTokenStorage;
import com.nlecloud.bc.model.PageResult;
import com.nlecloud.bc.model.User;
import com.nlecloud.bc.service.contract.IInfringementContractService;
import com.nlecloud.bc.util.FileUtil;
import com.nlecloud.bc.util.MD5Util;
import com.nlecloud.bc.util.ZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple6;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.model.TransactionReceipt;
import org.fisco.bcos.sdk.transaction.model.exception.ContractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author warrior
 * @description 侵权取证合约操作服务接口实现
 */
@Service
@Slf4j
public class InfringementContractService implements IInfringementContractService {

    @Value("${fisco.bcos.contract.infringement.address}")
    private String contractInfringementAddress;

    @Value("${file-save-path}")
    private String fileSavePath;

    @Autowired
    private Client client;

    @Autowired
    private PhantomjsConfig phantomjsConfig;

    @Override
    public boolean addInfringement(String title, String url, HttpServletRequest request) throws Exception {
        Infringement infringement = Infringement.load(contractInfringementAddress, client, client.getCryptoSuite().getCryptoKeyPair());
        String uuid = UUID.randomUUID().toString();
        //将侵权url信息存储图片
        String imageName = uuid + CustomerConstant.IMG_SUFFIX;
        String imagePath = fileSavePath + imageName;
        //将侵权url信息存储html
        String htmlFile = uuid + CustomerConstant.HTML_SUFFIX;
        String htmlPath = fileSavePath + htmlFile;
        phantomjsConfig.URL2HtmlAndImg(url, htmlPath, imagePath);
        //生成压缩文件
        List<String> fileList = new ArrayList<>();
        fileList.add(htmlPath);
        fileList.add(imagePath);
        String zipFileName = uuid + CustomerConstant.ZIP_SUFFIX;
        ZipUtil.compressFiles(fileSavePath, zipFileName, fileList);
        //删除图片文件
        FileUtil.deleteFile(imagePath);
        //删除html文件
        FileUtil.deleteFile(htmlPath);
        User user = AuthTokenStorage.getUser();
        String ownerId = user.getId();
        //String fileUrlPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + CustomerConstant.BASE_FOLDER + imageName;
        String hash = MD5Util.getFileMd5(fileSavePath + zipFileName);
        TransactionReceipt transactionReceipt = infringement.insertInfringement(uuid, title, hash, ownerId, url);
        log.info("add infringement traction receipt {}", transactionReceipt.toString());
        String status = transactionReceipt.getStatus();
        return CustomerConstant.SUCCESS_STATUS.equals(status);
    }

    @Override
    public PageResult<InfringementDTO> listInfringement(int index, int size, HttpServletRequest req) throws ContractException {
        Infringement infringement = Infringement.load(contractInfringementAddress, client, client.getCryptoSuite().getCryptoKeyPair());
        User user = AuthTokenStorage.getUser();
        String ownerId = user.getId();
        Tuple6<BigInteger, List<String>, List<String>, List<String>, List<String>, List<String>> tuple6 = infringement.selectInfringement(ownerId, new BigInteger(String.valueOf(index)), new BigInteger(String.valueOf(size)));

        long total = tuple6.getValue1().longValue();
        List<String> uuids = tuple6.getValue2();
        List<String> titles = tuple6.getValue3();
        List<String> hashs = tuple6.getValue4();
        List<String> ownerIds = tuple6.getValue5();
        List<String> urls = tuple6.getValue6();

        if (total == 0) {
            return PageResult.emptyPageResult(size, index);
        }

        List<InfringementDTO> infringementDTOS = new ArrayList<>(uuids.size());
        for (int i = 0; i < uuids.size(); i++) {
            InfringementDTO infringementDTO = new InfringementDTO();
            infringementDTO.setUuid(uuids.get(i));
            infringementDTO.setTitle(titles.get(i));
            infringementDTO.setHash(hashs.get(i));
            infringementDTO.setOwnerId(ownerIds.get(i));
            infringementDTO.setUrl(urls.get(i));
//            String imageFileName = FileUtil.searchFile(fileSavePath, uuids.get(i) + CustomerConstant.IMG_SUFFIX);
//            String path = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + imageFileName;
            String zipFileName = FileUtil.searchFile(fileSavePath, uuids.get(i) + CustomerConstant.ZIP_SUFFIX);
            String path = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + zipFileName;
            infringementDTO.setPath(path);
//            String htmlFileName = FileUtil.searchFile(fileSavePath, uuids.get(i) + CustomerConstant.HTML_SUFFIX);
//            String htmlPath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + htmlFileName;
//            infringementDTO.setHtmlPath(htmlPath);
            infringementDTOS.add(infringementDTO);
        }
        return PageResult.pagination(size, index, total, infringementDTOS);
    }
}
